<template>
  <div>
     <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
        <!-- 添加角色区域 -->
        <el-row>
            <el-col>
                <el-button type="primary" @click="addRolesFormVisible=true">添加角色</el-button>
            </el-col>
        </el-row>
         <!-- 表格区域 -->
            <el-table
                :data="rolesList"
                style="width: 100%"
                border
                stripe
                >
                <!-- 展开列 -->
                <el-table-column type="expand">
                    <template v-slot="scope">
                        <el-row v-for="(item1,i1) in scope.row.children" :key="item1.id" :class="['bdbottom',i1==0?'bdtop':'','vcenter']" >
                            <!-- 渲染一级权限 -->
                            <el-col :span="5">
                                <el-tag closable @close="removeItemById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 渲染二级和三级权限 -->
                            <el-col :span="19">
                                <el-row v-for="(item2,i2) in item1.children" :key="item2.id" :class="[i2==0?'':'bdtop','vcenter']">
                                    <!-- 二级 -->
                                    <el-col :span="6">
                                        <el-tag type="success" closable @close="removeItemById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>

                                    </el-col>
                                    <!-- 三级 -->
                                    <el-col :span="18">
                                        <el-tag v-for="(item3,i3) in item2.children" :key="item3.id" type="warning" closable @close="removeItemById(scope.row,item3.id)">{{item3.authName}}</el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                       <!-- <pre>
                        {{scope.row}}
                       </pre> -->
                    </template>
                </el-table-column>
                <!-- 索引列 -->
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column prop="roleName" label="角色名称"></el-table-column>
                <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
                <el-table-column label="操作" width="300px">
                    <template v-slot="scope">
                        <!-- 修改按钮 -->
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)">编辑</el-button>
                        <!-- 删除按钮 -->
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteRoles(scope.row.id)">删除</el-button>
                        <!-- 分配按钮 -->
                        <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配权限</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!-- 添加角色表单 -->
    <el-dialog title="添加角色" :visible.sync="addRolesFormVisible" width="50%" @close="addRolesDialog">
        <!-- 内容主体区 -->
        <el-form :model="addRolesForm" ref="addRolesRormRef"  label-width="70px">
            <el-form-item label="角色名称">
                <el-input v-model="addRolesForm.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述">
                <el-input v-model="addRolesForm.roleDesc"></el-input>
            </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <div slot="footer" class="dialog-footer">
            <el-button @click="addRolesFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="addRoles">确 定</el-button>
        </div>
    </el-dialog>

    <!-- 修改角色信息 -->
    <el-dialog
        title="修改角色信息"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editDialogClosed"
        >
        <el-form :model="editForm" ref="editRolesFormRef" label-width="70px">
            <el-form-item label="角色名称">
                <el-input v-model="editForm.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述">
                <el-input v-model="editForm.roleDesc"></el-input>
            </el-form-item>
            
            
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editRolesInfo">确 定</el-button>
        </span>
    </el-dialog>

    <!-- 分配角色权限 -->
    <el-dialog
        title="分配角色权限"
        :visible.sync="setRightsDialogVisible"
        width="50%"
        @close="defKeys=[]"
        >
        <el-tree :data="RightsList" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys" ref="treeRef"></el-tree>
        <span slot="footer" class="dialog-footer">
            <el-button @click="setRightsDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="setRolesRight">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
name:'Roles',
data() {
    return {
        addRolesFormVisible:false,
        rolesList:[],
        addRolesForm:{
            roleName:'',
            roleDesc:''
        },
        editDialogVisible:false,
        // 查询到的角色信息
        editForm:{},
        setRightsDialogVisible:false,
        RightsList:[],
        treeProps:{
            children: 'children',
            label: 'authName'
        },
        // 默认展开勾选的id值
        defKeys:[],
        // 即将分配的角色id
        roleId:''
    }
},
created() {
    this.getRolesList()
},
methods:{
    async getRolesList() {
        const {data:res}=await this.$http.get('roles')
        // console.log(res);
        if(res.meta.status!==200) return this.$message.error(res.meta.msg)
        this.rolesList=res.data
  
    },
    //   添加角色对话框关闭之后重置表单
      addRolesDialog() {
        this.$refs.addRolesRormRef.resetFields()
      },
      addRoles() {
        this.$refs.addRolesRormRef.validate(async valid=>{
            if(!valid) return
            // 可以发起添加角色的网络请求
            const {data:res}=await this.$http.post('roles',this.addRolesForm)
            // console.log(res);
            if(res.meta.status!==201) return this.$message.error('添加角色失败')
            this.$message.success('添加角色成功')
            this.addRolesFormVisible = false
            // 重新获取角色列表
            this.getRolesList()
        })
       
    },
    // 修改角色信息
    async showEditDialog(id) {
        this.editDialogVisible=true
        // console.log(id);
        const {data:res}=await this.$http.get(`roles/${id}`)
        // console.log(res);
        if(res.meta.status!==200) return this.$message.error('查询角色信息失败')
        this.editForm=res.data
    },
    //   修改角色对话框关闭之后重置表单
    editDialogClosed() {
        this.$refs.editRolesFormRef.resetFields()
    },
    // 修改角色信息并提交
    editRolesInfo() {
        this.$refs.editRolesFormRef.validate(async valid=>{
        if(!valid) return
        const {data:res}=await this.$http.put(`roles/${this.editForm.roleId}`,{
            roleName:this.editForm.roleName,
            roleDesc:this.editForm.roleDesc
        })
        // console.log(this.editForm);
        // console.log(res);
        if(res.meta.status!==200) return this.$message.error('修改角色信息失败')
        this.$message.success('修改角色信息成功')
        this.editDialogVisible = false
        this.getRolesList()
        })
    },
    // 删除角色
    async deleteRoles(id) {
        const comfirmResult=await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
        // 确认删除confirm
        // 取消删除concel
        // console.log(comfirmResult);
        if(comfirmResult!=='confirm') {
            return this.$message.info('取消了删除')
        }
        const {data:res}=await this.$http.delete('roles/'+id)
        if(res.meta.status!==200) return this.$message.error('删除角色信息失败')
        this.$message.success('删除角色信息成功')
        this.getRolesList()
    },
    // 删除权限
    async removeItemById(role,rightsid) {
        const confirmResult=await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
        if(confirmResult!=='confirm') {
            return this.$message.info('取消了删除')
        } 
        
        const {data:res}=await this.$http.delete('roles/'+role.id+'/rights/'+rightsid)
        if(res.meta.status!==200) return this.$message.error('删除权限失败')
        // this.getRolesList()
        role.children=res.data
        this.$message.success('删除权限成功')
        
    },
    async showSetRightDialog(role) {
        this.setRightsDialogVisible=true
        const {data:res}=await this.$http.get('rights/tree')
        if(res.meta.status!==200) return this.$message.error('获取权限数据失败')
        // 使用递归
        this.getDefKeys(role,this.defKeys)
        this.RightsList=res.data
        this.roleId=role.id
    },
    getDefKeys(node,arr) {
        if(!node.children) {
            return arr.push(node.id)
        }
        node.children.forEach(item => 
            this.getDefKeys(item,arr)
        );

    },
    async setRolesRight() {
        const keys=[
            ...this.$refs.treeRef.getCheckedKeys(),
            ...this.$refs.treeRef.getHalfCheckedKeys()
        ]
        const idStr=keys.join(',')
        const {data:res}=await this.$http.post('roles/'+this.roleId+'/rights',{rids:idStr})
        if(res.meta.status!==200) return this.$message.error('修改权限失败')
        this.$message.success('修改权限成功')
        this.getRolesList()
        this.setRightsDialogVisible=false
    }
}
}
</script>

<style scoped>
.el-tag {
    margin: 7px;
}
.bdtop {
    border-top: 1px solid #eee;
}
.bdbottom {
    border-bottom: 1px solid #eee;
}
td .el-row {
    margin: 0 30px;
}
.vcenter {
    display: flex;
    align-items: center;
}
</style>